﻿using UnityEngine;

//拖到摄影机
namespace CGF
{
    [ExecuteInEditMode]
    [RequireComponent(typeof(Camera))]
    public class CameraLookAround : MonoBehaviour
    {
        public bool canDrag = true;
        [Space]
        public Transform target;
        public float targetYOffset = 0;
        [Space]
        public float cameraAngleHor = 0;
        public float cameraAngleVer = 135;
        public float cameraDistance = 5;

        private Camera currCamera;
        private Vector3 previousPos, dragDelta;

        void Update()
        {
            if (!currCamera)
            {
                currCamera = GetComponent<Camera>();
            }

            if (target)
            {
                Vector3 targetPos = target.position + new Vector3(0, targetYOffset, 0);
                float radianY = cameraAngleHor * Mathf.Deg2Rad;
                Vector3 rotationAxis = new Vector3(Mathf.Sin(radianY), 0, Mathf.Cos(radianY));
                Quaternion rotation = Quaternion.AngleAxis(cameraAngleVer, rotationAxis.normalized);
                transform.position = targetPos + rotation * (Vector3.down * cameraDistance);
                transform.LookAt(targetPos);
            }

            if (canDrag)
            {
                if (Input.GetMouseButtonDown(0))
                {
                    OnTouchDown(currCamera.ScreenToViewportPoint(Input.mousePosition));
                }
                if (Input.GetMouseButton(0))
                {
                    OnTouchMove(currCamera.ScreenToViewportPoint(Input.mousePosition));
                }
                if (Input.GetMouseButtonUp(0))
                {
                    OnTouchUp();
                }
            }
        }

        void OnTouchDown(Vector3 pos)
        {
            previousPos = pos;
            dragDelta = Vector2.zero;
        }

        void OnTouchMove(Vector3 pos)
        {
            dragDelta = pos - previousPos;
            previousPos = pos;
            cameraAngleHor += dragDelta.x * 100;
            cameraAngleVer -= dragDelta.y * 100;
        }

        void OnTouchUp()
        {

        }
    }
}